package com.moive.news.tqnewsapplication.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.moive.news.tqnewsapplication.R;
import com.moive.news.tqnewsapplication.adapter.NewsAdapter;
import com.moive.news.tqnewsapplication.base.Adapter.BaseListAdapter;
import com.moive.news.tqnewsapplication.base.BaseFragment;
import com.moive.news.tqnewsapplication.entity.NewsInfo;
import com.moive.news.tqnewsapplication.networks.BaseApi;
import com.moive.news.tqnewsapplication.okmanager.OkManagerCallback;
import com.moive.news.tqnewsapplication.ui.activity.NewsDteilsAcitivity;
import com.moive.news.tqnewsapplication.utils.DateUtil;
import com.moive.news.tqnewsapplication.utils.GetSystemTimeUitl;
import com.moive.news.tqnewsapplication.utils.LogUtil;
import com.moive.news.tqnewsapplication.utils.PreferenceUtil;
import com.moive.news.tqnewsapplication.utils.ToastUtils;
import com.moive.news.tqnewsapplication.weight.mylistview.SecondXListView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * Created by Administrator on 2018/1/8.
 */

public class XiaodaoFragment extends BaseFragment  implements  SecondXListView.IXListViewListener{
    @BindView(R.id.pub_all_listview)
    SecondXListView pubAllListview;
    @BindView(R.id.pub_all_myText)
    TextView pubAllMyText;
    Unbinder unbinder;
    private View NewsListView;
    private List<NewsInfo.RowsBean> list = new ArrayList<>();
    private Gson gson = new Gson();
    private int page = 1;
    private boolean isfresh = true;
    private XiaoDaoAdapter adapter;
    private static final String TAG = "XiaodaoFragment";
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        NewsListView = inflater.inflate(R.layout.layout_recyclerview, container, false);
        unbinder = ButterKnife.bind(this, NewsListView);
        return NewsListView;
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
    }
    private void init() {
        adapter = new XiaoDaoAdapter(getActivity());
        pubAllListview.setAdapter(adapter);
        pubAllListview.setXListViewListener(this);
        pubAllListview.setPullLoadEnable(true);
        getdata();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
    @Override
    public void onRefresh() {
        page = 1;
        isfresh = true;
        list.clear();
        getdata();
        adapter.notifyDataSetChanged();
        stopOnLoad();
    }
    private void stopOnLoad() {
        pubAllListview.stopRefresh();
        pubAllListview.stopLoadMore();
        pubAllListview.setRefreshTime(GetSystemTimeUitl.getTime());
    }
    @Override
    public void onLoadMore() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                isfresh = false;
                getdata();
                adapter.notifyDataSetChanged();
                stopOnLoad();
            }
        }, 1000);
    }
    public void getdata() {
        OkHttpUtils.get()
                .url(BaseApi.NEWS_TYPE_ITEM)
                .addParams("token", PreferenceUtil.getString("token",""))
                .addParams("page", page + "")
                .addParams("rows", "10")
                .addParams("category", "小道")
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.i(TAG, "error=" + e.toString());
            }
            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, "response=" + response.toString());
                try {
                    JSONObject j = new JSONObject(response);
                    JSONArray j2 = j.getJSONArray("rows");
                    if (j2!=null||j2.length()!=0){
                        for (int i = 0; i < j2.length(); i++) {
                            JSONObject j3 = (JSONObject) j2.opt(i);
                            NewsInfo.RowsBean bean = gson.fromJson(j3 + "", NewsInfo.RowsBean.class);
                            list.add(bean);
                        }
                        adapter.addItems(list);
                    }else {
                        ToastUtils.ShortToast("没有更多数据了！");
                    }
                    pubAllListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            if (list.size()>0){
                                Intent i = new Intent(getActivity(), NewsDteilsAcitivity.class);
                                Bundle b = new Bundle();
                                b.putString("url", list.get(position-1).getId());
                                b.putString("comment",list.get(position-1).getTitle());
                                LogUtil.i("lidaming",list.get(position-1).getId());
                                i.putExtras(b);
                                startActivity(i);
                            }

                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public class XiaoDaoAdapter extends BaseListAdapter<NewsInfo.RowsBean> {
        Context context;
        public static final int TYPE_1 = 0;
        public static final int TYPE_2 = 1;
        public XiaoDaoAdapter(Context context) {
            this.context = context;
        }
        @Override
        protected View getItemView(int position, View convertView, ViewGroup parent, List<NewsInfo.RowsBean> item) {
           ViewHoder viewHolder = null;
            ViewHoder02 viewHoder02=null;
            int type = getItemViewType(position);
            if (convertView == null) {
                switch (type) {
                    case TYPE_1:
                        viewHolder = new ViewHoder();
                        convertView = LayoutInflater.from(context).inflate(R.layout.adapter_newsinfo, null);
                        viewHolder.news_img = convertView.findViewById(R.id.news_img);
                        viewHolder.news_src = convertView.findViewById(R.id.news_src);
                        viewHolder.news_time = convertView.findViewById(R.id.news_time);
                        viewHolder.news_title = convertView.findViewById(R.id.news_title);
                        convertView.setTag(viewHolder);
                        break;
                    case TYPE_2:
                        viewHoder02=new ViewHoder02();
                        convertView=LayoutInflater.from(context).inflate(R.layout.adpater_newsinfo_02,null);
                        viewHoder02.newsinfo_desrc = convertView.findViewById(R.id.newsinfo_desrc);
                        viewHoder02.newsinfo_time = convertView.findViewById(R.id.newsinfo_time);
                        viewHoder02.newsinfo_title = convertView.findViewById(R.id.newsinfo_title);
                        convertView.setTag(viewHoder02);
                        break;
                }
            } else {
                switch (type){
                    case TYPE_1:
                        viewHolder = (ViewHoder) convertView.getTag();
                        break;
                    case TYPE_2:
                        viewHoder02= (ViewHoder02) convertView.getTag();
                        break;
                }
            }
            switch (type){
                case TYPE_1:
                    Glide.with(context)
                            .load(item.get(position).getTitleImg())
                            .centerCrop()
                            .dontAnimate()
                            .placeholder(R.drawable.icon)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(viewHolder.news_img);
                    viewHolder.news_src.setText(item.get(position).getSrc());
                    viewHolder.news_title.setText(item.get(position).getTitle());
                    String newtime = DateUtil.getDescriptionTimeFromTimestamp(item.get(position).getTime());
                    viewHolder.news_time.setText(newtime);
                    break;
                case TYPE_2:
                    viewHoder02.newsinfo_desrc.setText(item.get(position).getSrc());
                    viewHoder02.newsinfo_title.setText(item.get(position).getTitle());
                    String newtime1 = DateUtil.getDescriptionTimeFromTimestamp(item.get(position).getTime());
                    viewHoder02.newsinfo_time.setText(newtime1);
                    break;
            }
            return convertView;
        }
        @Override
        public int getItemViewType(int position) {
            if (list != null & list.size() > 0) {
              if (!TextUtils.isEmpty(list.get(position).getTitleImg())){
                  return TYPE_1;
              }else {
                  return TYPE_2;
              }
            }
            return TYPE_2;
        }
        @Override
        public int getViewTypeCount() {
            return 2;
        }
        class ViewHoder {
            ImageView news_img;
            TextView news_title, news_src, news_time;
        }
        class ViewHoder02{
            TextView newsinfo_title, newsinfo_desrc, newsinfo_time;
        }
    }
}
